/**
 * 
 */
package com.moji.cyg.web.extend.session;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.moji.cyg.biz.user.UserModel;
import com.moji.cyg.common.json.JacksonHelper;
import com.moji.cyg.common.security.SecurityUtil;
import com.moji.cyg.web.model.CygWebConstant;

/**
 * 不允许有session存在
 * 
 * @author shengli.caosl 2012-2-28 下午11:20:17
 */
public class SessionUtil {

    private static final Logger logger = LoggerFactory.getLogger(SecurityUtil.class);

    public static void putRootDomainSession(HttpServletResponse response, String key, Object value, int aliveMinutes) {
        if (value == null) {
            return;
        }
        String temp = null;
        if (value instanceof String) {
            temp = (String) value;
        } else {
            temp = JacksonHelper.toJSON(value);
        }
        // 加密
        try {
            temp = SecurityUtil.encodeWord(temp);
        } catch (UnsupportedEncodingException e) {
            logger.error("Encode Word Error!" + temp, e);
        }
        Cookie cookie = new Cookie(key, temp);
        cookie.setMaxAge(60 * aliveMinutes);
        cookie.setDomain(CygWebConstant.WEB_ROOT_DOMAIN);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    public static void putLongLifeSession(HttpServletResponse response, String key, Object value) {
        if (value == null) {
            return;
        }
        String temp = null;
        if (value instanceof String) {
            temp = (String) value;
        } else {
            temp = JacksonHelper.toJSON(value);
        }
        // 加密
        try {
            temp = SecurityUtil.encodeWord(temp);
        } catch (UnsupportedEncodingException e) {
            logger.error("Encode Word Error!" + temp, e);
        }
        Cookie cookie = new Cookie(key, temp);
        cookie.setMaxAge(-1);
        cookie.setDomain(CygWebConstant.WEB_ROOT_DOMAIN);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    /**
     * @param request
     * @param key : session key
     * @param clazz : 返回类型
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getSession(HttpServletRequest request, String key, Class<T> clazz) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (key.equals(cookie.getName())) {
                String value = cookie.getValue();
                if (value == null) {
                    return null;
                }
                // 解密
                try {
                    value = SecurityUtil.decodeWord(value);
                    if (clazz == String.class) {
                        return (T) value;
                    }
                    return JacksonHelper.fromJSON(value, clazz);
                } catch (UnsupportedEncodingException e) {
                    logger.error("Decode Word Error!" + value, e);
                } catch (Exception e) {
                }
                break;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        UserModel userModel = new UserModel();
        userModel.setUserName("123");
        String result = JacksonHelper.toJSON(userModel);
        System.out.println(result);
        System.out.println(JacksonHelper.fromJSON(result, UserModel.class));
    }
}
